//
//  KABLoginVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABLoginVC.h"
#import "KABRegisterVC.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABModel.h"
#import "XDRsa.h"
#import "ApiManager.h"
#import <UINavigationBar+Awesome.h>
#import "WXApi.h"
#import "WXApiManager.h"

@interface KABLoginVC ()<WXApiManagerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *findPwdBtn;
@property (weak, nonatomic) IBOutlet UIButton *wechatBtn;
@property (weak, nonatomic) IBOutlet UIView *wechatBgView;

@end

@implementation KABLoginVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"登录";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
}

- (void)initSubViews {
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorLoginFontColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:14]};
    self.nameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:dic];
    self.pwdTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dic];
    
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = CGRectGetHeight(self.loginBtn.frame) / 2.0;
    [self.loginBtn addTarget:self action:@selector(loginBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.registerBtn addTarget:self action:@selector(registerBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.findPwdBtn addTarget:self action:@selector(findPwdBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.wechatBtn.layer.cornerRadius = CGRectGetWidth(self.wechatBtn.frame) / 2.0;
    self.wechatBtn.layer.borderWidth = 1;
    self.wechatBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.wechatBtn addTarget:self action:@selector(wechatBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.wechatBgView.hidden = ![WXApi isWXAppInstalled];
    
    self.nameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultsAccount];
    self.pwdTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultsPwd];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar lt_reset];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    NSLog(@"登录界面请求微信登录返回:code-%@, state-%@, lang-%@, country-%@", response.code, response.state, response.lang, response.country);
    
    if (response.errCode == 0) {
        [self requestWxLoginWithCode:response.code state:@"Kabu-iOS"];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"微信授权失败"];
    }
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self exitViewController];
}

- (void)loginBtnTapped:(UIButton *)btn {
    if (![self checkUserInput]) {
        return;
    }
    
    [self requestLogin];
}

- (void)registerBtnTapped:(UIButton *)btn {
    KABRegisterVC *vc = [[KABRegisterVC alloc] initWithViewType:KABRegisterVCTypeRegister];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)findPwdBtnTapped:(UIButton *)btn {
    KABRegisterVC *vc = [[KABRegisterVC alloc] initWithViewType:KABRegisterVCTypeFindPwd];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)wechatBtnTapped:(UIButton *)btn {
    [WXApiManager sharedManager].delegate = self;
    [self sendAuthRequest];
}

#pragma mark - private methods
-(void)sendAuthRequest {
    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"Kabu-iOS" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

- (BOOL)checkUserInput {
    if (!self.nameTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入手机号"];
        return NO;
    }
    
    if (!self.pwdTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入密码"];
        return NO;
    }
    
    return YES;
}

- (void)exitViewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - network request
- (void)requestLogin {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSInteger timestramp = [[NSDate date] timeIntervalSince1970];
    NSDictionary *dic = @{@"password" : self.pwdTextField.text,
                          @"timestamp": @(timestramp)};
    NSString *token = [XDRsa base64EncryptWithDictionary:dic];
    
    NSDictionary *pars = @{@"account"  : self.nameTextField.text,
                           @"token"    : token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiLogin] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
            [[KABModel sharedInstance] saveUserInfoWithPwd:self.pwdTextField.text];
            [self exitViewController];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestWxLoginWithCode:(NSString *)code state:(NSString *)state {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"code" : code,
                          @"state" : state};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiWXLogin] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] loginModelWithDictionary:responseObject];
            [[KABModel sharedInstance] saveWxAccessToken];
            [self exitViewController];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

@end
